import { Message } from 'element-ui'

// Message control configuration
const messageConfig = {
  maxConcurrent: 1, // Maximum concurrent messages
  minInterval: 500, // Minimum interval between messages (ms)
  groupSimilar: true, // Group similar messages
  defaultDuration: 2500, // Default message duration
  errorDuration: 4000 // Error message duration
}

// Message queue management
class MessageController {
  constructor() {
    this.messageInstance = null
    this.messageQueue = []
    this.lastMessageTime = 0
    this.lastMessageContent = ''
    this.similarMessageCount = 0
    this.processing = false
  }

  show(options) {
    const now = Date.now()
    
    // Check if this is a duplicate message
    if (options.message === this.lastMessageContent && 
        now - this.lastMessageTime < messageConfig.minInterval) {
      this.similarMessageCount++
      
      // Update existing message with count if grouping is enabled
      if (messageConfig.groupSimilar && this.messageInstance) {
        this.messageInstance.close()
        this.messageInstance = Message({
          ...options,
          message: `${options.message} (×${this.similarMessageCount + 1})`,
          duration: options.duration || messageConfig.defaultDuration
        })
      }
      return
    }

    // Reset similar message tracking
    if (options.message !== this.lastMessageContent) {
      this.similarMessageCount = 0
    }

    // Add to queue
    this.messageQueue.push(options)
    this.processQueue()
  }

  processQueue() {
    if (this.processing || this.messageQueue.length === 0) {
      return
    }

    const now = Date.now()
    const timeSinceLastMessage = now - this.lastMessageTime

    // Check minimum interval
    if (timeSinceLastMessage < messageConfig.minInterval && this.messageInstance) {
      setTimeout(() => this.processQueue(), messageConfig.minInterval - timeSinceLastMessage)
      return
    }

    this.processing = true
    const options = this.messageQueue.shift()

    // Close previous message if max concurrent is 1
    if (messageConfig.maxConcurrent === 1 && this.messageInstance) {
      this.messageInstance.close()
    }

    // Show the message
    this.messageInstance = Message({
      ...options,
      duration: options.duration || 
                (options.type === 'error' ? messageConfig.errorDuration : messageConfig.defaultDuration),
      onClose: () => {
        this.messageInstance = null
        this.processing = false
        
        // Process next message in queue
        if (this.messageQueue.length > 0) {
          setTimeout(() => this.processQueue(), 100)
        }
      }
    })

    this.lastMessageTime = now
    this.lastMessageContent = options.message
    this.processing = false
  }

  success(message) {
    this.show({ type: 'success', message })
  }

  error(message) {
    this.show({ type: 'error', message })
  }

  info(message) {
    this.show({ type: 'info', message })
  }

  warning(message) {
    this.show({ type: 'warning', message })
  }

  clear() {
    this.messageQueue = []
    if (this.messageInstance) {
      this.messageInstance.close()
      this.messageInstance = null
    }
  }
}

// Create singleton instance
const messageController = new MessageController()

// Override Element UI Message
const originalMessage = Message
const controlledMessage = function(options) {
  if (typeof options === 'string') {
    messageController.info(options)
  } else {
    messageController.show(options)
  }
}

// Add shorthand methods
controlledMessage.success = (msg) => messageController.success(msg)
controlledMessage.error = (msg) => messageController.error(msg)
controlledMessage.info = (msg) => messageController.info(msg)
controlledMessage.warning = (msg) => messageController.warning(msg)

// Export both controlled and original
export { controlledMessage, originalMessage, messageController }

// Install as Vue plugin
export default {
  install(Vue) {
    // Replace global $message with controlled version
    Vue.prototype.$message = controlledMessage
    Vue.prototype.$messageController = messageController
    Vue.prototype.$originalMessage = originalMessage
  }
}